
# UI_module/ui_main_window.py
import datetime
import socket
from PySide6.QtCore import Qt, Signal, Slot, QTimer
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget

class Ui_MainWindow(QWidget):
    dataUpdated = Signal(str)  # 定义一个信号，用于通知数据更新

    def __init__(self):
        super().__init__()
        self.setupUi()
        self.last_update_time = None  # 用于记录最后一次更新的时间
        self.timer = QTimer(self)  # 创建一个定时器
        self.timer.timeout.connect(self.checkUpdate)  # 连接定时器的超时信号到 checkUpdate 槽函数
        self.timer.start(500)  # 设置定时器每 500 毫秒触发一次

    def setupUi(self):
        self.setObjectName(u"MainWindow")
        self.resize(200, 200)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(9, 9, 9, 9)
        layout.setSpacing(3)

        hostname = socket.gethostname()
        ip_address = socket.gethostbyname(hostname)
        #port = "xxxx"
        port=socket.getsockname()[1]

        self.ip_port_label = QLabel(f"IP: {ip_address}, Port: {port}", self)
        self.ip_port_label.setAlignment(Qt.AlignLeft)
        self.ip_port_label.setFixedWidth(210)
        self.ip_port_label.setFixedHeight(20)
        layout.addWidget(self.ip_port_label)

        self.placeholder_label = QLabel("Placeholder text", self)
        self.placeholder_label.setAlignment(Qt.AlignLeft)
        layout.addWidget(self.placeholder_label)

        self.dynamic_text_label = QLabel("Initial Text", self)
        self.dynamic_text_label.setAlignment(Qt.AlignCenter)
        self.dynamic_text_label.setFixedHeight(40)
        layout.addWidget(self.dynamic_text_label)

        # 连接信号和槽
        self.dataUpdated.connect(self.updateDynamicTextLabel)

    @Slot(str)
    def updateDynamicTextLabel(self, new_text):
        """更新动态文本标签的内容"""
        self.dynamic_text_label.setText(new_text)
        self.last_update_time = datetime.datetime.now()  # 更新最后更新时间

    def checkUpdate(self):
        """检查是否需要更新文本"""
        if self.last_update_time is not None:
            time_since_last_update = datetime.datetime.now() - self.last_update_time
            if time_since_last_update.total_seconds() > 0.5:
                self.dynamic_text_label.setText("--waiting--")
                self.last_update_time = None  # 重置最后更新时间